package com.lz.netty.producer.project.netty;

import com.lz.netty.producer.project.netty.codec.ObjDecoder;
import com.lz.netty.producer.project.netty.codec.ObjEncoder;
import com.lz.netty.producer.project.netty.domain.MsgInfo;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;
/**
 * 处理连接和业务逻辑：在 ChannelInitializer 中添加自定义的 ChannelHandler 来处理连接和业务逻辑。
 *
 *
 * @author Administrator*/
public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel channel) {
        //对象传输处理
        channel.pipeline().addLast(new ObjDecoder(MsgInfo.class));
        channel.pipeline().addLast(new ObjEncoder(MsgInfo.class));
        // 心跳时间 心跳机制
        channel.pipeline().addLast("idle", new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
        // 对http协议的支持.
        channel.pipeline().addLast(new HttpServerCodec());
        // 对大数据流的支持
        channel.pipeline().addLast(new ChunkedWriteHandler());
        // 聚合 Http 将多个requestLine、requestHeader、messageBody信息转化成单一的request或者response对象
        channel.pipeline().addLast(new HttpObjectAggregator(8192));
        // 聚合 websocket 的数据帧，因为客户端可能分段向服务器端发送数据
        channel.pipeline().addLast(new WebSocketFrameAggregator(1024 * 62));
        // 在管道中添加我们自己的接收数据实现方法
        channel.pipeline().addLast(new MyServerHandler());
    }

}
